<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
        >
            <el-form-item label="主题名称" prop="projectName">
                <el-input
                    v-model="queryParams.projectName"
                    placeholder="请输入"
                    clearable
                    size="small"
                />
            </el-form-item>
            <el-form-item label="培训类型" prop="projectType">
                <el-select
                    v-model="queryParams.projectType"
                    placeholder="请选择"
                    :style="{ width: '100%' }"
                >
                    <el-option
                        v-for="item in projectTypeOptions"
                        :key="item.dictCode"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="addTheme"
                    >新增</el-button
                >
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    >删除</el-button
                >
            </el-col> -->
        </el-row>
        <el-table
            v-loading="loading"
            :data="themeList"
            @selection-change="handleSelectionChange"
        >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column
                label="主题名称"
                align="center"
                prop="projectName"
            />
            <el-table-column
                label="培训类型"
                align="center"
                prop="projectTypeName"
            />
            <el-table-column label="培训内容" align="center" prop="remark" />
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-if="userId == scope.row.createUserId"
                        >修改</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="createTrainProject(scope.row)"
                        >创建培训项目</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-if="userId == scope.row.createUserId"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="65%"
            append-to-body
        >
            <el-form
                ref="newTrainform"
                :model="newTrainform"
                :rules="newTrainformRules"
                label-width="120px"
            >
                <el-form-item label="主题名称" prop="projectName">
                    <el-input
                        v-model="newTrainform.projectName"
                        placeholder="请输入主题名称"
                    />
                </el-form-item>
                <el-form-item label="培训类型" prop="projectType">
                    <el-select
                        v-model="newTrainform.projectType"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in projectTypeOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="培训内容" prop="remark">
                    <el-input
                        v-model="newTrainform.remark"
                        placeholder="请填写培训内容"
                        class="textarea"
                        type="textarea"
                    />
                </el-form-item>
                <el-form-item
                    label="课程选择"
                    prop="courseList[0]"
                    :rules="[
                        {
                            required: true,
                            message: '请选择课程',
                            trigger: 'blur'
                        }
                    ]"
                >
                    <el-button
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="courseopen = true"
                        >选择课程</el-button
                    >
                    <el-table
                        v-loading="loading"
                        :data="newTrainform.courseList"
                        style="height: 200px;overflow-y: auto;"
                    >
                        <el-table-column
                            label="课程名称"
                            align="center"
                            prop="varName"
                        />
                        <el-table-column
                            label="课程类别"
                            align="center"
                            prop="typeId"
                        />
                        <el-table-column
                            label="课程描述"
                            align="center"
                            prop="varDesc"
                        />
                        <el-table-column
                            label="学时"
                            align="center"
                            prop="intClassHour"
                        />
                        <el-table-column
                            label="试题数量"
                            align="center"
                            prop="questionCount"
                        />
                        <el-table-column
                            label="试用行业"
                            align="center"
                            prop="varIndustry"
                        />
                    </el-table>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitNewTrainform"
                    >确 定</el-button
                >
                <el-button @click="cancel('open')">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog
            title="创建培训项目"
            :visible.sync="addCourseOpen"
            :before-close="closeDialog"
            width="65%"
            append-to-body
        >
            <el-form
                ref="addUserForm"
                :model="addUserForm"
                :rules="addUserFormRules"
                label-width="120px"
            >
                <el-form-item label="培训名称" prop="projectName">
                    <el-input
                        v-model="addUserForm.projectName"
                        placeholder="请输入培训名称"
                    />
                </el-form-item>
                <el-form-item label="培训类型" prop="projectType">
                    <el-select
                        v-model="addUserForm.projectType"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in projectTypeOptions"
                            :key="item.dictCode"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="培训时间" prop="trainTime">
                    <el-date-picker
                        v-model="addUserForm.trainTime"
                        type="daterange"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="考试时间" prop="examTime">
                    <el-date-picker
                        v-model="addUserForm.examTime"
                        type="datetimerange"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="考试次数" prop="examNum">
                    <el-input
                        v-model="addUserForm.examNum"
                        placeholder="请输入考试次数"
                    />
                </el-form-item>
                <el-form-item
                    label="课程选择"
                    prop="courseList[0]"
                    :rules="[
                        {
                            required: true,
                            message: '请选择课程',
                            trigger: 'blur'
                        }
                    ]"
                >
                    <el-button
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="courseopen = true"
                        >选择课程</el-button
                    >
                    <el-table
                        v-loading="loading"
                        :data="courseList"
                        style="height: 200px;overflow-y: auto;"
                    >
                        <el-table-column
                            label="课程名称"
                            align="center"
                            prop="varName"
                        />
                        <el-table-column
                            label="课程类别"
                            align="center"
                            prop="typeId"
                        />
                        <el-table-column
                            label="课程描述"
                            align="center"
                            prop="varDesc"
                        />
                        <el-table-column
                            label="学时"
                            align="center"
                            prop="intClassHour"
                        />
                        <el-table-column
                            label="试用行业"
                            align="center"
                            prop="varIndustry"
                        />
                    </el-table>
                </el-form-item>
                <el-form-item
                    label="人员选择"
                    prop="personList[0]"
                    :rules="[
                        {
                            required: true,
                            message: '请选择课程',
                            trigger: 'blur'
                        }
                    ]"
                >
                    <el-button
                        type="primary"
                        icon="el-icon-search"
                        size="mini"
                        @click="useropen = true"
                        >选择人员</el-button
                    >
                    <el-table
                        v-loading="loading"
                        :data="UserList"
                        style="height: 200px;overflow-y: auto;"
                    >
                        <el-table-column
                            label="姓名"
                            align="center"
                            prop="nickName"
                        />
                        <el-table-column
                            label="单位"
                            align="center"
                            prop="dept.deptName"
                        />
                    </el-table>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="addLoading"
                    >确 定</el-button
                >
                <el-button @click="cancel('addCourseOpen')">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 选择课程 -->
        <el-dialog
            title="选择课程"
            :visible.sync="courseopen"
            width="65%"
            append-to-body
        >
            <selectCourse @selectFn="selectCourseFn"></selectCourse>
        </el-dialog>
        <!-- 选择人员 -->
        <el-dialog
            title="选择人员"
            :visible.sync="useropen"
            width="65%"
            append-to-body
        >
            <selectUsers @selectFn="selectUserFn"></selectUsers>
        </el-dialog>
    </div>
</template>
<script>
import { addTrainTheme, getTrainThemeList, editTrainTheme, deleteTrainTheme, getTrainThemeDetail } from '@/api/system/train'
import { addTrainProject } from "@/api/system/education";
import selectCourse from '@/components/selectCourse'
import selectUsers from '@/components/selectUsers'
export default {
    name: '',
    components: {
        selectCourse,
        selectUsers
    },
    data () {
        const examNumReg = (rule, value, callback) => {
            let r = /^[1-9]\d*$/;
            if (value === '' || value === undefined) {
                callback(new Error('请输入课考试次数!'));
            } else if (!r.test(value)) {
                callback(new Error('请输入一个正整数!'));
            } else {
                callback()
            }
        }
        return {
            loading: false,
            addLoading: false,
            open: false,
            title: '',
            ids: [],
            addCourseOpen: false,
            courseopen: false,
            useropen: false,
            multiple: true,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                projectName: '',
                projectType: ''
            },
            themeList: [],
            newTrainform: {
                projectName: '', // 主题名称
                projectType: '', // 培训类型
                remark: '', // 培训内容
                courseList: [] // 课程
            },
            newTrainformRules: {
                projectName: [
                    { required: true, message: '请输入主题名称', trigger: 'blur' }
                ],
                projectType: [
                    { required: true, message: '请选择培训类型', trigger: 'blur' }
                ],
                remark: [
                    { required: true, message: '请选择培训n内容', trigger: 'blur' }
                ],
                'courseList[0]': [
                    { required: true, message: '请选择课程', trigger: 'blur' }
                ]
            },
            addUserForm: {
                projectName: undefined,
                projectType: undefined,
                examNum: undefined,
                trainStartTime: undefined,
                trainEndTime: undefined,
                examStartTime: undefined,
                examEndTime: undefined,
                trainTime: undefined,
                examTime: undefined,
                courseList: [],
                personList: []
            },
            addUserFormRules: {
                projectName: [
                    { required: true, message: "请输入项目名称", trigger: ['blur'] }
                ],
                projectType: [
                    { required: true, message: "请选择培训类型", trigger: ['blur'] }
                ],
                examNum: [
                    { validator: examNumReg, trigger: 'blur' },
                    { required: true, message: "请输入课考试次数", trigger: ['blur'] }
                ],
                trainTime: [
                    { required: true, message: "请选择培训时间", trigger: ['blur'] }
                ],
                examTime: [
                    { required: true, message: "请选择考试时间", trigger: ['blur'] }
                ],
                'courseList[0]': [
                    { required: true, message: '请选择课程', trigger: 'blur' }
                ],
                'personList[0]': [
                    { required: true, message: '请选择人员', trigger: 'blur' }
                ]
            },
            courseList: [],
            UserList: [], // 选中的人员集合
            projectTypeOptions: [], // 培训类别
            userId: '',
            currentTrainTheme: null
        }
    },
    created () {
        this.getDicts("train_type").then(response => {
            this.projectTypeOptions = response.data;
        });
        this.getList()
        this.userId = this.$store.state.user.userId
    },
    methods: {
        addTheme () {
            this.newTrainform = {
                projectName: '', // 主题名称
                projectType: '', // 培训类型
                remark: '', // 培训内容
                courseList: [] // 课程
            }
            this.open = true
            this.title = "新增培训主题"
        },
        handleUpdate (item) {
            this.open = true
            this.title = "修改主题信息"
            this.getTrainThemeDetail(item.themeId)
        },
        createTrainProject (row) {
            this.addCourseOpen = true
            this.currentTrainTheme = row
            this.courseList = this.currentTrainTheme.courseList
            this.addUserForm.projectName = row.projectName
            this.addUserForm.projectType = row.projectType
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.themeId)
            this.multiple = !selection.length
        },
        selectCourseFn (selectedIds, clearSelected) { // 添加课程回调
            if (selectedIds.length == 0) {
                this.$message.error('请选择课程')
            } else {
                //  console.log(selectedIds)
                if (this.addCourseOpen) {
                    this.courseList = selectedIds
                } else {
                    this.newTrainform.courseList = selectedIds;
                }
                this.courseopen = false
                clearSelected() // 清除选中的table状态
            }
        },
        selectUserFn (selectedIds, clearSelected) { // 添加人员回调
            if (selectedIds.length == 0) {
                this.$message.error('请选择人员')
            } else {
                // console.log(selectedIds)
                this.UserList = selectedIds;
                clearSelected() // 清除选中的table状态
                this.useropen = false
            }
        },
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const ids = row.themeId || this.ids;
            this.$confirm('是否确认删除培训主题名称为"' + row.projectName + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return deleteTrainTheme({
                    id: ids
                });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () { });
        },
        getList () {
            this.loading = true;
            getTrainThemeList(this.queryParams).then((res) => {
                this.themeList = res.data;
                this.total = res.total;
                this.loading = false;
            })
        },
        projectTypeFormatter (item) {
            for (let i = 0; i < this.projectTypeOptions.length; i++) {
                if (item.projectType == this.projectTypeOptions[i].dictLabel) {
                    return this.projectTypeOptions[i].dictValue
                }
            }
            return item.projectType
        },
        submitNewTrainform () {
            this.$refs["newTrainform"].validate(valid => {
                if (valid) {
                    let params = Object.assign({}, this.newTrainform)
                    params.courseList = params.courseList.map(item => {
                        return {
                            id: item.id
                        }
                    })
                    params.projectType = this.projectTypeFormatter(params)
                    if (!this.newTrainform.themeId) {
                        addTrainTheme(params).then(() => {
                            this.msgSuccess("新增成功");
                            this.open = false
                            this.getList()
                        })
                    } else {
                        editTrainTheme(params).then(() => {
                            this.msgSuccess("修改成功");
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        cancel (key) {
            this[key] = false
            if (key == 'addCourseOpen') {
                this.resetAddUserForm()
            }
        },
        submitForm () {
            this.addUserForm.personList = []
            this.addUserForm.courseList = []
            let params = Object.assign({}, this.addUserForm)
            //课程
            for (let i = 0; i < this.courseList.length; i++) {
                let cobj = {
                    'id': this.courseList[i].id,
                    'questionCount': this.courseList[i].questionCount
                };
                params.courseList.push(cobj);
            }
            //人员
            for (let i = 0; i < this.UserList.length; i++) {
                let uobj = {
                    'userId': this.UserList[i].userId
                };
                params.personList.push(uobj);
            }
            this.$refs["addUserForm"].validate(valid => {
                if (valid) {
                    this.addLoading = true
                    params.trainStartTime = this.addUserForm.trainTime[0];
                    params.trainEndTime = this.addUserForm.trainTime[1];
                    params.examStartTime = this.addUserForm.examTime[0];
                    params.examEndTime = this.addUserForm.examTime[1];
                    addTrainProject(params).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess("新增成功");
                            this.addCourseOpen = false;
                            this.resetAddUserForm()
                        }
                    }).finally(() => {
                        this.addLoading = false
                    });
                }
            })
        },
        closeDialog (done) {
            this.resetAddUserForm()
            done()
        },
        resetAddUserForm () {
            this.addUserForm = {
                projectName: undefined,
                projectType: undefined,
                examNum: undefined,
                trainStartTime: undefined,
                trainEndTime: undefined,
                examStartTime: undefined,
                examEndTime: undefined,
                trainTime: undefined,
                examTime: undefined,
                courseList: [],
                personList: []
            }
            this.UserList = []
            this.courseList = []
        },
        getTrainThemeDetail (themeId) {
            let params = {
                themeId: themeId
            }
            getTrainThemeDetail(params).then(res => {
                let item = res.data
                for (const key in this.newTrainform) {
                    this.newTrainform[key] = item[key]
                }
                this.newTrainform.themeId = item.themeId
            })
        }
    }
}
</script>
<style scoped>
.textarea >>> textarea {
    height: 120px;
}
</style>
